package com.petecapra.cashflow.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.petecapra.cashflow.model.Account;
import com.petecapra.cashflow.model.dao.AccountManager;

@Controller
@RequestMapping("/accounts*")
public class AccountsController {
	
	@Autowired private AccountManager accountManager;

	@RequestMapping(method = RequestMethod.GET)
    public String list(ModelMap modelMap) {
        modelMap.addAttribute("accounts", accountManager.getAll());
        return "accounts/list";
    }
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String show(@PathVariable("id") long id, ModelMap modelMap) {
        Account account = accountManager.findById(id);
        modelMap.addAttribute("accounts", accountManager.getAll());
        modelMap.addAttribute("account", account);
        modelMap.addAttribute("firstTransaction", account.getFirstUnpaidTransaction());
        modelMap.addAttribute("lastTransaction", account.getLastUnpaidTransaction());
        modelMap.addAttribute("accountTransactions", account.getUnpaidTransactions());
        return "accounts/view";
    }
	
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String create(ModelMap modelMap) {
		modelMap.addAttribute("accounts", accountManager.getAll());
        modelMap.addAttribute("account", new Account());
        return "accounts/form";
	}
	
	@RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
	public String update(ModelMap modelMap) {
		modelMap.addAttribute("accounts", accountManager.getAll());
        modelMap.addAttribute("account", new Account());
        return "accounts/form";
	}
	
	@RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
	public String delete(@PathVariable("id") long id, ModelMap modelMap) {
		Account account = accountManager.findById(id);
		modelMap.addAttribute("accounts", accountManager.getAll());
        modelMap.addAttribute("account", account);
        return "accounts/delete";
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	public String delete(@PathVariable("id") long id) {
		Account account = accountManager.findById(id);
		accountManager.delete(account);
        return "redirect:/accounts";
	}
	
	@Transactional
	@RequestMapping(value = "", method = RequestMethod.POST)	
	public String create(Account account, ModelMap modelMap) {
		accountManager.save(account);
		return "redirect:accounts/" + account.getId();
	}	
	
}

